package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.SensitiveDto;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.service.WmSensitiveService;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
* @author 马毅爽
* @description 针对表【wm_sensitive(敏感词信息表)】的数据库操作Service实现
* @createDate 2023-12-17 15:28:50
*/
@Service
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive>
    implements WmSensitiveService{

    @Override
    public ResponseResult listByDto(SensitiveDto dto) {
        // 1. 检查参数
        if (dto == null || dto.getSize() == null || dto.getPage() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 获取分页参数
        Page<WmSensitive> p = new Page<WmSensitive>(dto.getPage(),dto.getSize()).addOrder(new OrderItem("created_time", false));
        // 3. 条件查询
        Page<WmSensitive> page = lambdaQuery()
                .like(dto.getName() != null,WmSensitive::getSensitives,dto.getName())
                .page(p);
        // 4. 返回结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int)page.getTotal());

        return result.ok(page.getRecords());
    }

    @Override
    @Transactional
    public ResponseResult saveOrUpdateOne(WmSensitive sensitive) {
        // 1. 检查参数
        if (sensitive == null || sensitive.getSensitives() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (sensitive.getId() == null){
            WmSensitive one = lambdaQuery()
                    .eq(WmSensitive::getSensitives, sensitive.getSensitives())
                    .one();
            if (one != null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
        }
        // 3. 补全参数
        sensitive.setCreatedTime(new Date());
        saveOrUpdate(sensitive);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult delete(Integer id) {
        // 检查参数
        if(id == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}




